#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main() {
    int pipefd[2]; // 用于存储管道的文件描述符
    pid_t cpid;
    char buf;
    char *message = "Hello from parent process!";

    // 创建管道
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (cpid == 0) {    /* 子进程读取管道 */
        close(pipefd[1]);          // 关闭写端

        printf("Child process reading from pipe:\n");
        while (read(pipefd[0], &buf, 1) > 0) {
            write(STDOUT_FILENO, &buf, 1);
        }

        write(STDOUT_FILENO, "\n", 1);
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);

    } else {            /* 父进程写入管道 */
        close(pipefd[0]);          // 关闭读端

        printf("Parent process writing to pipe:\n");
        write(pipefd[1], message, strlen(message));
        close(pipefd[1]);          // 写完后关闭写端

        wait(NULL);                // 等待子进程结束
        exit(EXIT_SUCCESS);
    }
}